package com.training2.bookstore.product.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import javax.servlet.ServletOutputStream;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.web.multipart.MultipartFile;

@Service
public class StorageService {
	@Value("${spring.servlet.multipart.location}")
	private String fileTempPath;
	
	public String store(MultipartFile file) {
		String fileName = file.getOriginalFilename();
		String[] ss = fileName.split("\\.");
		String rawFileName = ss[0];// .subBefore(fileName, ".", true);
		String fileType = ss[1];// StrUtil.subAfter(fileName, ".", true);
		String documentId = rawFileName + "-" + UUID.randomUUID();
		String localFilePath = fileTempPath +  "/"+ documentId + "." + fileType;

		try {
			file.transferTo(new File(localFilePath));
		} catch (Exception e) {
			throw new RuntimeException(e);

		}

		return documentId + "."	+ fileType;

	}

	public void read(ServletOutputStream out, String documentId) {
		String fullPath = fileTempPath + "/" + documentId;

		try {
			InputStream in = new FileInputStream(fullPath);
			StreamUtils.copy(in, out);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	
}
